package com.toymate.common.utils;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.sse.EventSources;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * HttpUtils
 *
 * @author weirdor (179946422@qq.com)
 * @version v1.0.0
 */
@Slf4j
public class HttpUtils {

    public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
    public final static int MAX_IDLE_CONNECTIONS = 20;
    public final static long KEEP_ALIVE_DURATION = 30L;

    public final static int CONNECT_TIME_OUT = 6;

    public final static int WRITE_TIME_OUT = 10;

    public final static int READ_TIME_OUT = 40;


    /**
     * client
     * 配置重试
     */
    private final static OkHttpClient HTTP_CLIENT = new OkHttpClient.Builder()
            .connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS)
            .writeTimeout(WRITE_TIME_OUT, TimeUnit.SECONDS)
            .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS)
            .connectionPool(new ConnectionPool(MAX_IDLE_CONNECTIONS, KEEP_ALIVE_DURATION, TimeUnit.MINUTES))
            .build();


    public static boolean stream(String url, Map<String, String> headers, String json, EventSourceListener eventSourceListener) {
        try {
            RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json);
            Request.Builder builder = new Request.Builder();
//            buildHeader(builder, headers);
            Request request = builder.url(url).post(body).build();
            EventSource.Factory factory = EventSources.createFactory(HTTP_CLIENT);
            //创建事件
            log.info("http stream请求,url: {},参数: {}", url, json);
            factory.newEventSource(request, eventSourceListener);
            return true;
        } catch (Exception e) {
            log.error("http stream请求，url: {} 失败 ,参数: {}", url, json, e);
        }
        return false;
    }
}
